<script setup lang="ts">
import {onMounted, ref} from "vue";
import init, {complex_calc} from "@/wasm/complex_calc";

const log = ref("");

function jsComplexCalc(input: Float32Array, iterations: number) {
  const output = new Float32Array(input.length);
  for (let i = 0; i < input.length; i++) {
    let sum = 0;
    for (let j = 0; j < iterations; j++) {
      const x = input[i] * Math.PI;
      sum += Math.abs(Math.sin(x) * Math.cos(x) + Math.sqrt(x * 2));
    }
    output[i] = sum / iterations;
  }
  return output;
}

async function run() {
  await init();
  const size = 1000000;
  const iterations = 1000;
  const input = new Float32Array(size);
  for (let i = 0; i < size; i++) {
    input[i] = Math.random() * 10;
  }

  const t0 = performance.now();
  const jsResult = jsComplexCalc(input, iterations);
  const t1 = performance.now();

  const output = new Float32Array(size);
  const t2 = performance.now();
  complex_calc(input, output, iterations);
  const t3 = performance.now();

  log.value = `JS: ${((t1 - t0) / 1000).toFixed(3)} s\nWASM: ${(
      (t3 - t2) / 1000
  ).toFixed(3)} s\n结果差异: ${Math.abs(jsResult[0] - output[0]).toFixed(6)}`;
}

onMounted(run)

</script>}

<template>
  <div :style="{border: '1px solid red'}">
    <button @click="run">重新运行</button>
    <pre>{{ log }}</pre>
  </div>
</template>

<style scoped>

</style>
